package com.uaf.vxalipaybill.provider.service.write.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Store;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;

import com.google.gson.reflect.TypeToken;
import com.sun.mail.imap.IMAPFolder;
import com.uaf.aop.BuryLog;
import com.uaf.aop.OperateEnum;
import com.uaf.api.vo.req.BaseReqVo;
import com.uaf.api.vo.resp.BaseRespVo;
import com.uaf.common.constant.utils.GlobalConstantParamUtils;
import com.uaf.common.date.utils.DateUtils;
import com.uaf.common.file.FileOperateUtil;
import com.uaf.common.ip.utils.IpUtils;
import com.uaf.common.json.utils.JsonUtils;
import com.uaf.common.security.utils.Base64Utils;
import com.uaf.common.thread.utils.ThreadPoolUtils;
import com.uaf.filesystem.vo.req.FtpUploadReqDataVo;
import com.uaf.filesystem.vo.resp.NfsFileDetailRespDataVo;
import com.uaf.http.HttpClientService;
import com.uaf.http.WebClientService;
import com.uaf.log.MySlf4j;
import com.uaf.redis.JedisClientTemplate;
import com.uaf.vxalipaybill.api.exception.VxAlipayBillException;
import com.uaf.vxalipaybill.api.exception.VxAlipayBillServiceException;
import com.uaf.vxalipaybill.api.vo.req.VxAlipayBillAuthReqVo;
import com.uaf.vxalipaybill.api.vo.req.VxAlipayBillNotifyReqVo;
import com.uaf.vxalipaybill.api.vo.resp.VxAlipayBillAuthRespVo;
import com.uaf.vxalipaybill.provider.bean.PdfBean;
import com.uaf.vxalipaybill.provider.bean.PdfDeatilBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayAnalysisDetailBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayAnalysisRespBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayBillAnalysisReqBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayBillArchiveInfoBean;
import com.uaf.vxalipaybill.provider.bean.VxAlipayMerchantConfigBean;
import com.uaf.vxalipaybill.provider.config.Config;
import com.uaf.vxalipaybill.provider.dao.VxAlipayAnalysisDetailBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayAnalysisRespBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayBillAnalysisReqBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayBillArchiveInfoBeanDao;
import com.uaf.vxalipaybill.provider.dao.VxAlipayMerchantConfigBeanDao;
import com.uaf.vxalipaybill.provider.lisener.MailListener;
import com.uaf.vxalipaybill.provider.service.write.IVxAlipayBillWriteService;
import com.uaf.vxalipaybill.provider.utils.VxAlipayBillConstantUtils;
import com.uaf.vxalipaybill.provider.utils.ZipUtils;

/**
 * @filename VxAlipayBillWriteServiceImpl.java
 * @description 微信支付宝账单服务类
 * @author 马庆智
 * @date 2021/9/15 11:06
 */
@Service
public class VxAlipayBillWriteServiceImpl implements IVxAlipayBillWriteService {

	@Autowired
	private Config config;

	@Autowired
	private MailListener mailListener;

	@Autowired
	private HttpClientService httpClientService;

	@Autowired
	private WebClientService webClientService;

	@Autowired
	private VxAlipayAnalysisRespBeanDao vxAlipayAnalysisRespBeanDao;

	@Autowired
	private VxAlipayAnalysisDetailBeanDao vxAlipayAnalysisDetailBeanDao;

	@Autowired
	private VxAlipayBillAnalysisReqBeanDao vxAlipayBillAnalysisReqBeanDao;

	@Autowired
	private VxAlipayBillArchiveInfoBeanDao vxAlipayBillArchiveInfoBeanDao;

	@Autowired
	private VxAlipayMerchantConfigBeanDao vxAlipayMerchantConfigBeanDao;

	@Autowired
	private JedisClientTemplate redisClientTemplate;

	@Autowired
	private TransactionTemplate transactionTemplate;

	/**
	 * 功能描述 微信支付宝账单授权解析
	 * @param  req   微信支付宝请求入参
	 * @return vxAlipayBillAuthRespVo 授权状态
	 * @author马庆智
	 * @date 2021/9/10 10:04
	 */
	@Override
	@BuryLog(OperateProcess = OperateEnum.OperateProcess.LICENESE_INFO, OperateProcessNode = OperateEnum.OperateProcessNode.VX_ALIPAY_BILL_DATA_COLLECT, ApplyCodeField = "data.businessId")
	@Transactional
	public VxAlipayBillAuthRespVo vxAlipayAuth(BaseReqVo<VxAlipayBillAuthReqVo> req) {
		VxAlipayBillAuthRespVo vxAlipayBillAuthRespVo = new VxAlipayBillAuthRespVo();
		String businessId = req.getData().getBusinessId();
		String str = redisClientTemplate
				.hmget(VxAlipayBillConstantUtils.BILL_REDIS_PREFIX.concat(businessId), req.getData().getAuthCode());
		if (null != str) {
			MySlf4j.textInfo("命中redis缓存挡板,业务编号:{0},账单类型:{1}", businessId, req.getData().getBillType());
			vxAlipayBillAuthRespVo.setAuthStatus(VxAlipayBillConstantUtils.STATUS_FAIL);
			return vxAlipayBillAuthRespVo;
		}

		ThreadPoolUtils threadPoolUtils = ThreadPoolUtils.getInstance().initThreadPool(10, 10, 100);

		// 获取商户信息
		VxAlipayMerchantConfigBean merchantConfigBean = vxAlipayMerchantConfigBeanDao
				.queryVxAlipayMerchantInfo(req.getMerchantId());
		if (null == merchantConfigBean) {
			throw new VxAlipayBillServiceException(VxAlipayBillException.ERR_100004);
		}
		/**如果是查询到的时授权成功状态或者授权失败状态,直接返回状态值*/
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean = getVxAlipayAuthState(req,
				merchantConfigBean.getCacheDays());
		if (vxAlipayBillAnalysisReqBean != null) {
			if (VxAlipayBillConstantUtils.STATUS_ING.equals(vxAlipayBillAnalysisReqBean.getStatus())) {
				vxAlipayBillAuthRespVo.setAuthStatus(VxAlipayBillConstantUtils.STATUS_ING);
				return vxAlipayBillAuthRespVo;
			}
			if (VxAlipayBillConstantUtils.STATUS_SUCCESS.equals(vxAlipayBillAnalysisReqBean.getStatus())
					|| VxAlipayBillConstantUtils.STATUS_LOCAL.equals(vxAlipayBillAnalysisReqBean.getStatus())) {
				boolean cacheFlag = isCache(businessId, vxAlipayBillAnalysisReqBean, merchantConfigBean.getCacheDays());
				if (cacheFlag) {
					vxAlipayBillAuthRespVo.setAuthStatus(VxAlipayBillConstantUtils.STATUS_SUCCESS);
					return vxAlipayBillAuthRespVo;
				}
			}
		}

		Integer billAnalysisReqId = saveVxAlipayBillAnalysisReqBean(VxAlipayBillConstantUtils.STATUS_ING, req);

		// 保证数据库事务执行成功后在执行异步操作
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				threadPoolUtils.execute(() -> {
					getAuthMethod(req, billAnalysisReqId);
				});
			}
		});

		vxAlipayBillAuthRespVo.setAuthStatus(VxAlipayBillConstantUtils.STATUS_ING);
		return vxAlipayBillAuthRespVo;
	}

	/**
	 * 功能描述 微信支付宝缓存处理
	 * @param businessId  业务编号
	 * @param  vxAlipayBillAnalysisReqBean 查询到的请求表Bean
	 * @param cacheDays 缓存天数
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/26 15:34
	 */
	@Override
	public boolean isCache(String businessId, VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean,
			Integer cacheDays) {
		vxAlipayBillAnalysisReqBean.setCacheDays(cacheDays);
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisCacheBean = vxAlipayBillAnalysisReqBeanDao
				.queryVxAlipayBillAnalysisDataByCache(vxAlipayBillAnalysisReqBean);

		if (null == vxAlipayBillAnalysisCacheBean) {
			return false;
		}

		/**当授权状态为成功1,bussinessId不同,copy请求及响应记录，并将status标识为 4：本地缓存*/
		if (!vxAlipayBillAnalysisCacheBean.getBussinessId().equals(businessId)) {

			/**通过bussinssId和source等参数查询状态为4的数据,看如何15天内是否复制过了1的状态*/
			vxAlipayBillAnalysisReqBean.setBussinessId(businessId);
			int count = vxAlipayBillAnalysisReqBeanDao.checkVxalipayBillIsExists(vxAlipayBillAnalysisReqBean);

			if (count <= 0) {
				/**copy并保存最新的请求表信息,并返回主键id*/
				int billAnalysisReqId = saveVxAlipayBillAnalysisReqBeanCopy(businessId, vxAlipayBillAnalysisCacheBean);
				/**copy并保存最新的归档表信息,并返回主键id*/
				saveVxAlipayBillArchiveInfoBeanCopy(businessId, vxAlipayBillAnalysisCacheBean);
				/**copy并保存最新的响应信息*/
				saveVxAlipayAnalysisRespBeanCopy(vxAlipayBillAnalysisCacheBean, billAnalysisReqId);
				/**copy并保存最新的响应详细信息*/
				saveVxAlipayAnalysisDetailBeanCopy(vxAlipayBillAnalysisCacheBean, billAnalysisReqId);
			}
		}

		return true;
	}

	/**
	 * 功能描述 copy并保存最新的请求表信息
	 * @param businessId  业务编号
	 * @param vxAlipayBillAnalysisReqBean 请求表Bean
	 * @return int 主键id
	 * @author 马庆智
	 * @date 2021/9/27 14:34
	 */
	private int saveVxAlipayBillAnalysisReqBeanCopy(String businessId,
			VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean) {
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBeanCache = new VxAlipayBillAnalysisReqBean();
		BeanUtils.copyProperties(vxAlipayBillAnalysisReqBean, vxAlipayBillAnalysisReqBeanCache);
		/**设置copy请求表不同的参数*/
		vxAlipayBillAnalysisReqBeanCache.setStatus(VxAlipayBillConstantUtils.STATUS_LOCAL);
		vxAlipayBillAnalysisReqBeanCache.setBussinessId(businessId);
		vxAlipayBillAnalysisReqBeanCache.setCreatedDate(new Date());
		vxAlipayBillAnalysisReqBeanCache.setCreatedBy("admin");
		vxAlipayBillAnalysisReqBeanCache.setUpdatedDate(new Date());
		vxAlipayBillAnalysisReqBeanCache.setUpdatedBy("admin");
		/**保存copy请求表*/;
		vxAlipayBillAnalysisReqBeanDao.saveVxAlipayBillAnalysisReqBean(vxAlipayBillAnalysisReqBeanCache);
		return vxAlipayBillAnalysisReqBeanCache.getBillAnalysisReqId();
	}

	/**
	 * 功能描述 copy并保存最新的响应详细信息
	 * @param vxAlipayBillAnalysisReqBean    请求表
	 * @param billAnalysisReqId 请求表copy生成最新的主键id
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/27 14:34
	 */
	private void saveVxAlipayAnalysisDetailBeanCopy(VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean,
			int billAnalysisReqId) {
		List<VxAlipayAnalysisDetailBean> vxAlipayAnalysisDetailBeanList = vxAlipayAnalysisDetailBeanDao
				.queryVxAlipayAnalysisDetailBeanByBillAnalysisReqId(
						vxAlipayBillAnalysisReqBean.getBillAnalysisReqId() + "");
		if (null != vxAlipayAnalysisDetailBeanList && vxAlipayAnalysisDetailBeanList.size() > 0) {
			for (VxAlipayAnalysisDetailBean vxAlipayAnalysisDetailBeanParam : vxAlipayAnalysisDetailBeanList) {
				VxAlipayAnalysisDetailBean vxAlipayAnalysisDetailBeanCache = new VxAlipayAnalysisDetailBean();
				BeanUtils.copyProperties(vxAlipayAnalysisDetailBeanParam, vxAlipayAnalysisDetailBeanCache);
				/**设置请求表copy生成最新的主键id*/
				vxAlipayAnalysisDetailBeanCache.setBillAnalysisReqId(billAnalysisReqId + "");
				vxAlipayAnalysisDetailBeanCache.setCreatedDate(new Date());
				vxAlipayAnalysisDetailBeanCache.setCreatedBy("admin");
				vxAlipayAnalysisDetailBeanCache.setUpdatedDate(new Date());
				vxAlipayAnalysisDetailBeanCache.setUpdatedBy("admin");
				vxAlipayAnalysisDetailBeanDao.saveVxAlipayAnalysisDetailBean(vxAlipayAnalysisDetailBeanCache);
			}
		}
	}

	/**
	 * 功能描述 copy并保存最新的响应详细信息
	 * @param businessId   bussinessId
	 * @param vxAlipayBillAnalysisReqBean 请求表
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/27 14:34
	 */
	private void saveVxAlipayBillArchiveInfoBeanCopy(String businessId,
			VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean) {
		VxAlipayBillArchiveInfoBean vxAlipayBillArchiveInfoBeanParam = new VxAlipayBillArchiveInfoBean();
		vxAlipayBillArchiveInfoBeanParam.setBussinessId(vxAlipayBillAnalysisReqBean.getBussinessId());
		vxAlipayBillArchiveInfoBeanParam.setSource(vxAlipayBillAnalysisReqBean.getSource());
		vxAlipayBillArchiveInfoBeanParam.setMerchantId(vxAlipayBillAnalysisReqBean.getMerchantId());
		vxAlipayBillArchiveInfoBeanParam.setCertNo(vxAlipayBillAnalysisReqBean.getCertNo());
		VxAlipayBillArchiveInfoBean vxAlipayBillArchiveInfoBean = vxAlipayBillArchiveInfoBeanDao
				.queryVxAlipayBillArchiveInfoBeanByParamBean(vxAlipayBillArchiveInfoBeanParam);
		if (null != vxAlipayBillArchiveInfoBean) {
			VxAlipayBillArchiveInfoBean vxAlipayBillArchiveInfoBeanCache = new VxAlipayBillArchiveInfoBean();
			BeanUtils.copyProperties(vxAlipayBillArchiveInfoBean, vxAlipayBillArchiveInfoBeanCache);
			/**设置请求表copy生成最新的主键id*/
			vxAlipayBillArchiveInfoBeanCache.setBussinessId(businessId);
			vxAlipayBillArchiveInfoBeanCache.setCreatedDate(new Date());
			vxAlipayBillArchiveInfoBeanCache.setCreatedBy("admin");
			vxAlipayBillArchiveInfoBeanCache.setUpdatedDate(new Date());
			vxAlipayBillArchiveInfoBeanCache.setUpdatedBy("admin");
			vxAlipayBillArchiveInfoBeanDao.saveVxAlipayBillArchiveInfoBean(vxAlipayBillArchiveInfoBeanCache);

		}
	}

	/**
	 * 功能描述 copy并保存最新的响应详细信息
	 * @param vxAlipayBillAnalysisReqBean    请求表
	 * @param billAnalysisReqId 请求表copy生成最新的主键id
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/27 14:34
	 */
	private void saveVxAlipayAnalysisRespBeanCopy(VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean,
			int billAnalysisReqId) {
		VxAlipayAnalysisRespBean vxAlipayAnalysisRespBean = vxAlipayAnalysisRespBeanDao
				.queryVxAlipayAnalysisRespBeanByBillAnalysisReqId(
						vxAlipayBillAnalysisReqBean.getBillAnalysisReqId() + "");
		if (null != vxAlipayAnalysisRespBean) {
			VxAlipayAnalysisRespBean vxAlipayAnalysisRespBeanCache = new VxAlipayAnalysisRespBean();
			BeanUtils.copyProperties(vxAlipayBillAnalysisReqBean, vxAlipayAnalysisRespBeanCache);
			/**设置请求表copy生成最新的主键id*/
			vxAlipayAnalysisRespBeanCache.setBillAnalysisReqId(billAnalysisReqId + "");
			vxAlipayAnalysisRespBeanCache.setCreatedDate(new Date());
			vxAlipayAnalysisRespBeanCache.setCreatedBy("admin");
			vxAlipayAnalysisRespBeanCache.setUpdatedDate(new Date());
			vxAlipayAnalysisRespBeanCache.setUpdatedBy("admin");
			vxAlipayAnalysisRespBeanDao.saveVxAlipayAnalysisRespBean(vxAlipayAnalysisRespBeanCache);

		}
	}

	/**
	 * 功能描述 查询微信支付宝授权状态
	 * @param req   请求入参
	 * @return com.uaf.vxalipaybill.provider.bean.VxAlipayBillAnalysisReqBean 微信支付宝请求实体类返回实体类
	 * @author 马庆智
	 * @date 2021/9/23 17:59
	 */
	private VxAlipayBillAnalysisReqBean getVxAlipayAuthState(BaseReqVo<VxAlipayBillAuthReqVo> req, int cacheDay) {
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean = new VxAlipayBillAnalysisReqBean();
		vxAlipayBillAnalysisReqBean.setSource(req.getData().getBillType());
		vxAlipayBillAnalysisReqBean.setCertNo(req.getData().getCertNo());
		vxAlipayBillAnalysisReqBean.setMerchantId(req.getMerchantId());
		vxAlipayBillAnalysisReqBean.setCacheDays(cacheDay);

		return vxAlipayBillAnalysisReqBeanDao.queryVxAlipayBillAnalysisReqBean(vxAlipayBillAnalysisReqBean);
	}

	/**
	 * 功能描述   微信支付宝授权过程
	 * @param req   授权过程入参
	 * @author马庆智
	 * @date 2021/9/22 15:19
	 */
	private void getAuthMethod(BaseReqVo<VxAlipayBillAuthReqVo> req, Integer billAnalysisReqId) {
		try {
			long begin = System.currentTimeMillis();
			dealVxAlipayBill(req, billAnalysisReqId);
			MySlf4j.textInfo("微信支付宝账单授权过程完成,businessId:{0},耗时(ms):{1}", req.getData().getBusinessId(),
					(System.currentTimeMillis() - begin));
		} catch (Exception e) {
			MySlf4j.textError("微信支付宝账单授权异常,businessId:{0},异常信息:{1}", req.getData().getBusinessId(),
					MySlf4j.ExceptionToString(e));
			dealAuthFail(req, billAnalysisReqId, "系统异常");
		}
	}

	/**
	 * 微信支付宝账单处理核心类
	 * 1、下载15天内的数据到本地服务器
	 * 2、通过客户输入的解压码循环解压本地压缩包
	 * 3、解压成功后识别pdf内容
	 * 4、推送识别结果
	 * @param req 授权请求参数
	 * @param billAnalysisReqId 主键ID
	 * @return void
	 * @author 王承
	 * @date 2021/12/11 14:52
	 */
	private void dealVxAlipayBill(BaseReqVo<VxAlipayBillAuthReqVo> req, Integer billAnalysisReqId) {
		ThreadPoolUtils threadPoolUtils = ThreadPoolUtils.getInstance().initThreadPool(10, 10, 100);
		String merchantId = req.getMerchantId();   // 商户号
		String businessId = req.getData().getBusinessId();  //业务编号
		String certNo = req.getData().getCertNo();  //身份证号
		String billType = req.getData().getBillType();   //账单类型
		String authCode = req.getData().getAuthCode();   //授权码
		boolean archiveFlag = false;        //归档标识
		boolean vxUpZipFlag = false;   //微信解压标识
		boolean alipayUpZipFlag = false;   //支付宝解压标识

		for (int i = 0; i < config.daySize; i++) {
			if (archiveFlag) {
				break;
			}

			String currentDate = DateUtils
					.dateToStr(DateUtils.beforeDate(new Date(), i), DateUtils.DATE_DEFAULT_FORMAT);
			String sftpFilePath = config.downloadUrl + "/" + currentDate;    //ftp路径
			String sftpBackupFilePath = config.historyUrl + "/" + currentDate;    //ftp归档路径
			String localFilePath = config.localUrl + "/" + merchantId + "/" + billAnalysisReqId + "/" + billType + "/"
					+ currentDate; //本地路径
			String localDelFilePath = config.localUrl + "/" + req.getMerchantId() + "/" + billAnalysisReqId; //本地删除路径

			/**判断ftp服务器是否存在文件夹*/
			if (FileOperateUtil.isFileExist(sftpFilePath)) {
				/**判断本地服务器是否存在文件夹,如果不存在就创建*/
				if (!FileOperateUtil.isFileExist(localFilePath)) {
					FileOperateUtil.createFolders(localFilePath);
				}

				try {
					// 批量下载压缩包
					FileOperateUtil.fileCopy(sftpFilePath, localFilePath, req.getData().getBillType());
				} catch (Exception ex) {
					MySlf4j.textWarn("微信支付宝账单授权未下载到对应压缩包,businessId:{0},billType:{1}", businessId, billType);
				}

				/**排序,按命名截取的最新数字进行排序,防止pdf格式压缩包和其他格式的压缩包混淆,取不到最新的记录*/
				List<String> listFiles = Arrays.asList(new File(localFilePath).list()).stream()
						.filter(x -> x.contains(".zip") && x.contains(billType)).sorted(new Comparator<String>() {
							@Override
							public int compare(String o1, String o2) {
								if (Integer.valueOf(o1.split("_")[1].split("\\.")[0]) < Integer
										.valueOf(o2.split("_")[1].split("\\.")[0])) {
									return 1;
								} else if (Integer.valueOf(o1.split("_")[1].split("\\.")[0]) == Integer
										.valueOf(o2.split("_")[1].split("\\.")[0])) {
									return 0;
								} else {
									return -1;
								}
							}
						}).collect(Collectors.toList());

				for (String billFileName : listFiles) {

					// 1 解压压缩包
					if (ZipUtils.unzipAll(localFilePath + "/" + billFileName, localFilePath, authCode)) {

						if (VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_ALIPAY.equals(billType)) {
							vxUpZipFlag = true;
						}
						if (VxAlipayBillConstantUtils.VX_ALIPAY_SOURCE_VX.equals(billType)) {
							alipayUpZipFlag = true;
						}
						threadPoolUtils.execute(() -> {
							try {
								// 2 将请求数据(业务编码,授权码等)加入归档表
								Map archive = new HashMap();
								archive.put("fileName", billFileName);
								archive.put("filePath", localFilePath);
								archive.put("achiveFilePath", sftpBackupFilePath);
								saveVxAlipayBillArchiveInfoBean(req, archive);

								// 3 pdf解析
								String pdfValue = distinguishPdf(req, archive);

								if (StringUtils.isNotBlank(pdfValue)) {
									PdfBean pdfBean = JsonUtils.fromJson(pdfValue, PdfBean.class);
									/**证件号码和识别的证件号码对比,匹配相同更新:成功*/
									if (req.getData().getCertNo().equalsIgnoreCase(pdfBean.getCertNo())
											|| config.isTest) {
										/**保存远程识别的pdf到响应表中*/
										saveVxAlipayOCRData(pdfBean, billAnalysisReqId + "");

										/**解析成功推送数据*/
										pushVxAlipayBill(req, VxAlipayBillConstantUtils.STATUS_SUCCESS, 3);

										/**pdf上传到文件服务器*/
										String base64Str = getPdfEncode64(archive, req.getData().getBusinessId(),
												sftpFilePath, sftpBackupFilePath, billFileName);
										NfsFileDetailRespDataVo filesystemResp = uploadPdf(req, archive, base64Str);
										if (null == filesystemResp) {
											updateVxAlipayBillAnalysisReqBean(VxAlipayBillConstantUtils.STATUS_FAIL,
													req, null, billAnalysisReqId);
										} else {
											updateVxAlipayBillAnalysisReqBean(VxAlipayBillConstantUtils.STATUS_SUCCESS,
													req, filesystemResp, billAnalysisReqId);
										}

										/**成功解析后删除本地临时目录的文件**/
										FileOperateUtil.fileDelete(localDelFilePath);

										// 4 归档
										if (!config.isTest) {
											FileOperateUtil.fileMove(sftpFilePath, sftpBackupFilePath, billFileName);
										}
									} else {
										MySlf4j.textError(
												"证件号码和识别的证件号码不匹配,businessId:{0},certNo:{1},ocrCertNo:{2},billType:{3}",
												businessId, certNo, pdfBean.getCertNo(), billType);
										/**证件号码和识别的证件号码对比,匹配不相同更新:更新:失败*/
										dealAuthFail(req, billAnalysisReqId, "证件号码和识别的证件号码不匹配");
									}
								} else {
									MySlf4j.textError("微信支付宝账单识别失败,businessId:{0},billType:{1}", businessId, billType);
									/**远程识别pdf失败,解析状态,3授权失败*/
									dealAuthFail(req, billAnalysisReqId, "微信支付宝账单识别失败");
								}
							} catch (VxAlipayBillServiceException ex) {
								dealAuthFail(req, billAnalysisReqId, "微信支付宝账单识别OR归档异常");
							} catch (Exception ex) {
								MySlf4j.textError("微信支付宝账单识别OR归档异常,businessId:{0},billType:{1},异常信息:{2}", businessId,
										billType, MySlf4j.ExceptionToString(ex));
								dealAuthFail(req, billAnalysisReqId, "微信支付宝账单识别OR归档异常");
							}
						});

						archiveFlag = true;
						break;
					}
				}
			}
		}

		/** 循环15天压缩包仍未命中，推送失败状态 */
		if (!vxUpZipFlag && !alipayUpZipFlag) {
			MySlf4j.textWarn("微信支付宝账单未匹配到对应压缩包,businessId:{0},billTye:{1}", businessId, billType);
			dealAuthFail(req, billAnalysisReqId, "微信支付宝账单未匹配到对应压缩包");
		}
	}

	/**
	 * 功能描述 处理授权失败的系列操作
	 * @param req  请求入参
	 * @param billAnalysisReqId 请求id
	 * @param msg  异常消息
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/30 16:32
	 */
	private void dealAuthFail(BaseReqVo<VxAlipayBillAuthReqVo> req, int billAnalysisReqId, String msg) {
		String businessId = req.getData().getBusinessId();
		String authCode = req.getData().getAuthCode();

		redisClientTemplate
				.hset(VxAlipayBillConstantUtils.BILL_REDIS_PREFIX.concat(businessId), authCode, msg, config.redisTime);
		updateVxAlipayBillAnalysisReqBean(VxAlipayBillConstantUtils.STATUS_FAIL, req, null, billAnalysisReqId);
		/**解析失败推送数据*/
		pushVxAlipayBill(req, VxAlipayBillConstantUtils.STATUS_FAIL, 3);

		/**解析操作完成后删除本地临时目录的文件**/
		String localDelFilePath = config.localUrl + "/" + req.getMerchantId() + "/" + billAnalysisReqId;
		FileOperateUtil.fileDelete(localDelFilePath);
	}

	/**
	 * 保存微信支付宝账单归档信息
	 * @param req 请求参数
	 * @return com.uaf.vxalipaybill.provider.bean.VxAlipayBillArchiveInfoBean
	 * @author 王承
	 * @date 2021/9/23 10:16
	 */
	private void saveVxAlipayBillArchiveInfoBean(BaseReqVo<VxAlipayBillAuthReqVo> req, Map<String, String> urlMap) {
		MySlf4j.textInfo("保存微信支付宝账单归档信息,businessId:{0},参数:{1}", req.getData().getBusinessId(), JsonUtils.toJson(req));
		VxAlipayBillArchiveInfoBean vxAlipayBillArchiveInfoBean = new VxAlipayBillArchiveInfoBean();
		vxAlipayBillArchiveInfoBean.setMerchantId(req.getMerchantId());
		vxAlipayBillArchiveInfoBean.setBussinessId(req.getData().getBusinessId());
		vxAlipayBillArchiveInfoBean.setCustName(req.getData().getCustName());
		vxAlipayBillArchiveInfoBean.setCertNo(req.getData().getCertNo());
		vxAlipayBillArchiveInfoBean.setSource(req.getData().getBillType());
		if (urlMap != null) {
			vxAlipayBillArchiveInfoBean.setArchiveName(urlMap.get("fileName"));
			vxAlipayBillArchiveInfoBean
					.setArchiveTime(DateUtils.dateToStr(new Date(), DateUtils.DATETIME_DEFAULT_FORMAT));
			vxAlipayBillArchiveInfoBean.setArchivePath(urlMap.get("achiveFilePath"));
			vxAlipayBillArchiveInfoBean
					.setArchiveTime(DateUtils.dateToStr(new Date(), DateUtils.DATETIME_DEFAULT_FORMAT));
		}
		vxAlipayBillArchiveInfoBean.setAuthCode(req.getData().getAuthCode());
		vxAlipayBillArchiveInfoBean.setCreatedBy("admin");
		vxAlipayBillArchiveInfoBean.setCreatedDate(new Date());
		vxAlipayBillArchiveInfoBean.setUpdatedBy("admin");
		vxAlipayBillArchiveInfoBean.setUpdatedDate(new Date());

		vxAlipayBillArchiveInfoBeanDao.saveVxAlipayBillArchiveInfoBean(vxAlipayBillArchiveInfoBean);
	}

	/**
	 * 功能描述 pdf文件上传
	 * @param req  请求入参
	 * @return NfsFileDetailRespDataVo
	 * @author马庆智
	 * @date 2021/9/17 17:11
	 */
	public NfsFileDetailRespDataVo uploadPdf(BaseReqVo<VxAlipayBillAuthReqVo> req, Map<String, String> urlMap,
			String base64Str) {
		BaseReqVo<FtpUploadReqDataVo> baseReqVo = new BaseReqVo<FtpUploadReqDataVo>();
		baseReqVo.setMerchantId(req.getMerchantId());
		baseReqVo.setMerchantKey(req.getMerchantKey());
		/**所属系统*/
		baseReqVo.setSourceSystem(VxAlipayBillConstantUtils.PDF_FILE_SOURCE_SYSTEM);
		baseReqVo.setIp(IpUtils.getServerIpAddr());
		FtpUploadReqDataVo ftpUploadReqDataVo = new FtpUploadReqDataVo();

		ftpUploadReqDataVo.setBusinessId(req.getData().getBusinessId());
		ftpUploadReqDataVo.setBase64String(base64Str);
		ftpUploadReqDataVo.setFileName(getLocalPdfValue(urlMap));
		ftpUploadReqDataVo.setProId(VxAlipayBillConstantUtils.PDF_FILE_PRO_ID);
		/** 文件编码 */
		ftpUploadReqDataVo.setInfoNum(VxAlipayBillConstantUtils.PDF_FILE_INFO_NUM);
		ftpUploadReqDataVo.setUserId(VxAlipayBillConstantUtils.PDF_FILE_USER_ID);
		ftpUploadReqDataVo.setFileSource(VxAlipayBillConstantUtils.PDF_FILE_SOURCE);
		ftpUploadReqDataVo.setFiletype("pdf");
		baseReqVo.setData(ftpUploadReqDataVo);
		MySlf4j.textInfo("微信支付宝账单上传,businessId:{0},请求参数字节大小:{1}(KB)", req.getData().getBusinessId(),
				JsonUtils.toJson(baseReqVo).getBytes().length / 1023);
		String result = webClientService.postJson(config.fileSystemUrl, baseReqVo);
		MySlf4j.textInfo("微信支付宝账单上传,businessId:{0},响应参数:{1}", req.getData().getBusinessId(), JsonUtils.toJson(result));

		if (result == null) {
			MySlf4j.textInfo("微信支付宝账单上传异常,businessId:{0}", req.getData().getBusinessId());
			return null;
		} else {
			BaseRespVo<NfsFileDetailRespDataVo> baseRespVo = JsonUtils
					.fromJson(result, new TypeToken<BaseRespVo<NfsFileDetailRespDataVo>>() {
					}.getType());
			return baseRespVo.getData();
		}

	}

	/**
	 * 功能描述  微信支付宝账单解析结果推送
	 * @param req  请求入参
	 * @param status  授权状态
	 * @param count  推送重试次数
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/22 15:35
	 */
	private void pushVxAlipayBill(BaseReqVo<VxAlipayBillAuthReqVo> req, String status, int count) {
		VxAlipayBillNotifyReqVo vxAlipayBillNotifyReqVo = new VxAlipayBillNotifyReqVo();
		vxAlipayBillNotifyReqVo.setBusinessId(req.getData().getBusinessId());
		vxAlipayBillNotifyReqVo.setAuthStatus(status);
		vxAlipayBillNotifyReqVo.setBillType(req.getData().getBillType());
		vxAlipayBillNotifyReqVo.setCertNo(req.getData().getCertNo());
		MySlf4j.textInfo("微信支付宝账单解析结果推送,businessId:{0},推送请求参数:{1}", req.getData().getBusinessId(),
				JsonUtils.toJson(vxAlipayBillNotifyReqVo));
		String str = "";
		if (StringUtils.isNotBlank(req.getData().getNotifyUrl().trim())) {
			str = httpClientService
					.doPost(req.getData().getNotifyUrl().trim(), JsonUtils.toJson(vxAlipayBillNotifyReqVo));
		}
		Map<String, String> resultMap = new HashMap<>();
		if (StringUtils.isNotBlank(str)) {
			resultMap = JsonUtils.fromJson(str, Map.class);
		}
		if (resultMap != null && resultMap.size() > 0) {
			if (resultMap.get("code").equals(GlobalConstantParamUtils.RESULT_CODE_SUCC)) {
				MySlf4j.textInfo("壹融站,微信支付宝账单解析结果推送请求成功,businessId:{0}", req.getData().getBusinessId());
			} else {
				if (count > 0) {
					pushVxAlipayBill(req, status, count - 1);
				}
			}
		}
	}

	/**
	 * 功能描述  微信支付宝账单远程pdf识别
	 * @param  req  微信支付宝参数
	 * @param urlMap 解压zip返回的文件名,文件上传路径等
	 * @return java.lang.String 返回识别参数
	 * @author 马庆智
	 * @date 2021/9/14 10:36
	 */
	private String distinguishPdf(BaseReqVo<VxAlipayBillAuthReqVo> req, Map<String, String> urlMap) {
		String billFile = getPdfEncode64(urlMap, req.getData().getBusinessId(), null, null, null);
		String businessId = req.getData().getBusinessId();
		String billType = req.getData().getBillType();
		Map<String, String> map = new HashMap<String, String>();
		map.put("billFile", billFile);
		if ("VX".equals(req.getData().getBillType())) {
			map.put("billType", req.getData().getBillType());
		} else {
			map.put("billType", "Alipay");
		}
		long start = System.currentTimeMillis();
		String str = JsonUtils.toJson(map);
		MySlf4j.textInfo("调用微信支付宝账单识别接口请求,businessId:{0},billType:{1},请求参数字节大小:{2}(KB)", businessId, billType,
				str.getBytes().length / 1023);
		String respStr = httpClientService.doPost(config.pdf, str);
		MySlf4j.textInfo("[OVERLENGTH]调用微信支付宝账单识别接口响应,businessId:{0},billType:{1},耗时(ms):{2},响应参数:{3}", businessId,
				billType, (System.currentTimeMillis() - start), respStr);
		return respStr;
	}

	/**
	 * 功能描述 获取 pdf生成的base64位编码
	 * @param urlMap 解压返回相关参数
	 * @return java.lang.String  返回pdf生成的base64位编码
	 * @author 马庆智
	 * @date 2021/9/18 11:00
	 */
	private String getPdfEncode64(Map<String, String> urlMap, String businessId, String sftpFilePath,
			String sftpBackupFilePath, String billFileName) {
		String valueUrl = getLocalPdfValue(urlMap);
		byte[] bytes = null;
		try {
			bytes = FileOperateUtil.readBytes(new File(urlMap.get("filePath") + "/" + valueUrl));
		} catch (Exception e) {
			MySlf4j.textWarn("businessId:{0},对应的压缩包解压后的文件不是pdf格式的文件", businessId);
			try {
				if (StringUtils.isNotBlank(sftpBackupFilePath) && StringUtils.isNotBlank(sftpBackupFilePath)
						&& StringUtils.isNotBlank(billFileName)) {
					FileOperateUtil.fileMove(sftpFilePath, sftpBackupFilePath, billFileName);
				}
			} catch (Exception e1) {
				MySlf4j.textError("businessId:{0},删除pdf格式的压缩包删除失败,异常信息为:{1}", businessId,
						MySlf4j.ExceptionToString(e1));
			}
			throw new VxAlipayBillServiceException(VxAlipayBillException.ERR_100000);
		}
		try {
			return Base64Utils.encode(bytes);
		} catch (UnsupportedEncodingException e) {
			MySlf4j.textError("base64编码异常,异常信息:{0}", MySlf4j.ExceptionToString(e));
			throw new VxAlipayBillServiceException(VxAlipayBillException.ERR_100000);

		}
	}

	/**
	 * 功能描述 获取本地服务器中解压的pdf文件名
	 * @param urlMap 解压放回的url值
	 * @return java.lang.String 本地解压成功后的pdf文件名
	 * @author 马庆智
	 * @date 2021/9/18 10:38
	 */
	private String getLocalPdfValue(Map<String, String> urlMap) {
		String valueUrl = "";
		for (File file2 : new File(urlMap.get("filePath")).listFiles()) {
			if (file2.getName().contains("pdf")) {
				valueUrl = file2.getName();
			}
		}
		return valueUrl;
	}

	/***
	 * 功能描述   获取更新归档表的数据
	 * @param req  请求参数
	 * @param nfsFileDetailRespDataVo 远程上传文件相关参数
	 * @return com.uaf.vxalipaybill.provider.bean.VxAlipayBillArchiveInfoBean
	 * @author 马庆智
	 * @date 2021/9/22 15:37
	 */
	private VxAlipayBillArchiveInfoBean getVxAlipayBillArchiveInfoBeanUpdate(BaseReqVo<VxAlipayBillAuthReqVo> req,
			NfsFileDetailRespDataVo nfsFileDetailRespDataVo) {
		VxAlipayBillArchiveInfoBean vxAlipayBillArchiveInfoBeanUpdate = new VxAlipayBillArchiveInfoBean();
		vxAlipayBillArchiveInfoBeanUpdate.setCertNo(req.getData().getCertNo());
		vxAlipayBillArchiveInfoBeanUpdate.setMerchantId(req.getMerchantId());
		vxAlipayBillArchiveInfoBeanUpdate.setBussinessId(req.getData().getBusinessId());
		vxAlipayBillArchiveInfoBeanUpdate.setSource(req.getData().getBillType());
		vxAlipayBillArchiveInfoBeanUpdate.setUpdatedDate(new Date());
		vxAlipayBillArchiveInfoBeanUpdate.setUpdatedBy("admin");
		vxAlipayBillArchiveInfoBeanUpdate
				.setArchiveTime(DateUtils.dateToStr(new Date(), DateUtils.DATETIME_DEFAULT_FORMAT));
		if (nfsFileDetailRespDataVo != null) {
			vxAlipayBillArchiveInfoBeanUpdate.setArchivePath(nfsFileDetailRespDataVo.getFilePath());
			vxAlipayBillArchiveInfoBeanUpdate.setArchiveName(nfsFileDetailRespDataVo.getFileName());
		}
		return vxAlipayBillArchiveInfoBeanUpdate;
	}

	/***
	 * 功能描述 新增解析请求表
	 * @param status 授权状态
	 * @param req  请求参数
	 * @return java.lang.String 主键id
	 * @author马庆智
	 * @date 2021/9/14 18:19
	 */
	private Integer saveVxAlipayBillAnalysisReqBean(String status, BaseReqVo<VxAlipayBillAuthReqVo> req) {
		MySlf4j.textInfo("保存微信支付宝账单请求信息,businessId:{0},参数:{1}", req.getData().getBusinessId(), JsonUtils.toJson(req));
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean = new VxAlipayBillAnalysisReqBean();
		vxAlipayBillAnalysisReqBean.setMerchantId(req.getMerchantId());
		vxAlipayBillAnalysisReqBean.setBussinessId(req.getData().getBusinessId());
		vxAlipayBillAnalysisReqBean.setCustName(req.getData().getCustName());
		vxAlipayBillAnalysisReqBean.setCertNo(req.getData().getCertNo());
		vxAlipayBillAnalysisReqBean.setSource(req.getData().getBillType());
		vxAlipayBillAnalysisReqBean.setAnalysisDate(DateUtils.dateToStr(new Date(), DateUtils.DATETIME_DEFAULT_FORMAT));
		vxAlipayBillAnalysisReqBean.setStatus(status); /**识别标识*/
		vxAlipayBillAnalysisReqBean.setCreatedDate(new Date());
		vxAlipayBillAnalysisReqBean.setCreatedBy("admin");
		vxAlipayBillAnalysisReqBeanDao.saveVxAlipayBillAnalysisReqBean(vxAlipayBillAnalysisReqBean);
		return vxAlipayBillAnalysisReqBean.getBillAnalysisReqId();
	}

	/**
	 * 功能描述 更新微信支付宝账单请求数据
	 * @param status  授权状态
	 * @param req  请求入参
	 * @param nfsFileDetailRespDataVo  远程文件上传
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/22 15:47
	 */
	private void updateVxAlipayBillAnalysisReqBean(String status, BaseReqVo<VxAlipayBillAuthReqVo> req,
			NfsFileDetailRespDataVo nfsFileDetailRespDataVo, int billAnalysisReqId) {
		VxAlipayBillAnalysisReqBean vxAlipayBillAnalysisReqBean = new VxAlipayBillAnalysisReqBean();
		vxAlipayBillAnalysisReqBean.setBillAnalysisReqId(billAnalysisReqId);
		vxAlipayBillAnalysisReqBean.setStatus(status); /**识别标识*/
		if (nfsFileDetailRespDataVo != null) {
			vxAlipayBillAnalysisReqBean.setFileId(nfsFileDetailRespDataVo.getFileId() + "");
			vxAlipayBillAnalysisReqBean.setFileName(nfsFileDetailRespDataVo.getFileName());
			vxAlipayBillAnalysisReqBean.setFilePath(nfsFileDetailRespDataVo.getFilePath());
		}
		vxAlipayBillAnalysisReqBean.setUpdatedDate(new Date());
		vxAlipayBillAnalysisReqBean.setUpdatedBy("admin");
		vxAlipayBillAnalysisReqBean.setAnalysisDate(DateUtils.dateToStr(new Date(), DateUtils.DATETIME_DEFAULT_FORMAT));
		vxAlipayBillAnalysisReqBeanDao.updateVxAlipayBillAnalysisReqBean(vxAlipayBillAnalysisReqBean);
	}

	/**
	 * 功能描述 保存微信支付宝账单OCR识别数据
	 * @param pdfBean OCR识别内容
	 * @param billAnalysisReqId 主键ID
	 * @return void
	 * @author 马庆智
	 * @date 2021/9/23 10:39
	 */
	private void saveVxAlipayOCRData(PdfBean pdfBean, String billAnalysisReqId) {
		VxAlipayAnalysisRespBean vxAlipayAnalysisRespBean = new VxAlipayAnalysisRespBean();
		vxAlipayAnalysisRespBean.setBillAnalysisReqId(billAnalysisReqId);
		vxAlipayAnalysisRespBean.setRespCode(pdfBean.getCode());
		vxAlipayAnalysisRespBean.setRespMsg(pdfBean.getMessage());
		vxAlipayAnalysisRespBean.setBillType(pdfBean.getBillType());
		vxAlipayAnalysisRespBean.setBillNo(pdfBean.getBillNo());
		vxAlipayAnalysisRespBean.setCustName(pdfBean.getName());
		vxAlipayAnalysisRespBean.setCertNo(pdfBean.getCertNo());
		vxAlipayAnalysisRespBean.setAcctNo(pdfBean.getAcctNo());
		vxAlipayAnalysisRespBean.setBillDateFrm(pdfBean.getBillDateFrm());
		vxAlipayAnalysisRespBean.setBillDateTo(pdfBean.getBillDateTo());
		vxAlipayAnalysisRespBean.setCreatedDate(new Date());
		vxAlipayAnalysisRespBean.setCreatedBy("admin");
		vxAlipayAnalysisRespBeanDao.saveVxAlipayAnalysisRespBean(vxAlipayAnalysisRespBean);
		/**保存详细表*/
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
				saveAnalysisDetailBeans(pdfBean, billAnalysisReqId);
			}
		});

	}

	/**
	 * 功能描述 保存微信支付宝账单详细表
	 * @param pdfBean  识别的pdf
	 * @param billAnalysisReqId 请求id
	 * @return void
	 * @author 马庆智
	 * @date 2022/4/24 9:24
	 */
	private void saveAnalysisDetailBeans(PdfBean pdfBean, String billAnalysisReqId) {
		for (PdfDeatilBean pdfDeatilBean : pdfBean.getData()) {
			VxAlipayAnalysisDetailBean vxAlipayAnalysisDetailBean = new VxAlipayAnalysisDetailBean();
			vxAlipayAnalysisDetailBean.setBillAnalysisReqId(billAnalysisReqId);
			vxAlipayAnalysisDetailBean.setTransTo(pdfDeatilBean.getTraTo());
			vxAlipayAnalysisDetailBean.setTransDateTime(pdfDeatilBean.getTraDateTime());
			vxAlipayAnalysisDetailBean.setTransType(pdfDeatilBean.getTraType());
			vxAlipayAnalysisDetailBean.setTransTitle(pdfDeatilBean.getTraTitle());
			if (StringUtils.isNotBlank(pdfDeatilBean.getTraAmt())) {
				vxAlipayAnalysisDetailBean.setTransAmt(new BigDecimal(pdfDeatilBean.getTraAmt().trim()));
			}
			vxAlipayAnalysisDetailBean.setTransFrm(pdfDeatilBean.getTraFrm());
			vxAlipayAnalysisDetailBean.setTransNo(pdfDeatilBean.getTraNo());
			vxAlipayAnalysisDetailBean.setRemarks(pdfDeatilBean.getRemark());
			vxAlipayAnalysisDetailBean.setMertrano(pdfDeatilBean.getMerTraNo());
			vxAlipayAnalysisDetailBean.setCreatedDate(new Date());
			vxAlipayAnalysisDetailBean.setCreatedBy("admin");
			vxAlipayAnalysisDetailBeanDao.saveVxAlipayAnalysisDetailBean(vxAlipayAnalysisDetailBean);
		}
	}

	/**
	 * 功能描述  删除指定天数之前的邮件
	 * @param deleteDay 删除天数
	 * @author 马庆智
	 * @date 2021/9/28 14:08
	 */
	public void deleteMailContent(int deleteDay) {
		Store store = null;
		IMAPFolder imapFolder = null;
		try {
			store = mailListener.initConnect();
			Folder folder = store.getFolder("Inbox");
			folder.open(Folder.READ_WRITE);
			imapFolder = (IMAPFolder) folder;
			String dateStr = DateUtils
					.dateToStr(DateUtils.beforeDate(new Date(), deleteDay), DateUtils.DATE_DEFAULT_FORMAT);
			MySlf4j.textInfo("删除时间参数:{0}", dateStr);
			Message[] messages = mailListener.getDeleteMessages(dateStr, imapFolder);
			deleteMailContent(messages);
		} catch (Exception e) {
			MySlf4j.textError("邮箱服务器删除过程出异常:{0}", MySlf4j.ExceptionToString(e));
		} finally {
			try {
				imapFolder.close(true);
				store.close();
			} catch (Exception e) {
				MySlf4j.textError("关闭邮件服务器,异常信息:{0}", MySlf4j.ExceptionToString(e));
			}
		}

	}

	/**
	 * 功能描述  删除邮件
	 * @param messages  yo
	 * @return java.lang.String 返回字符串
	 * @author 马庆智
	 * @date 2021/9/9 14:58
	 */
	public void deleteMailContent(Message... messages) throws Exception {
		/** 解析所有邮件要删除的邮件*/
		for (int i = 0, count = messages.length; i < count; i++) {
			/** 邮件删除*/
			Message message = messages[i];
			message.setFlag(Flags.Flag.DELETED, true);
		}
	}

	/**
	 * 功能描述 本地pdf识别和文件上传
	 * @param req 请求参数
	 * @param urlMap  要解析的文件夹路径
	 * @author 马庆智
	 * @date 2021/10/18 15:42
	 */
	public void distinguishPdfAndUpload(BaseReqVo<VxAlipayBillAuthReqVo> req, Map<String, String> urlMap) {
		/**保存请求表*/
		int billAnalysisReqId = saveVxAlipayBillAnalysisReqBean(VxAlipayBillConstantUtils.STATUS_ING, req);
		/** 先把请求数据(业务编码,授权码等)加入归档表 */
		saveVxAlipayBillArchiveInfoBean(req, urlMap);

		/** 远程pdf解析 */
		String pdfValue = distinguishPdf(req, urlMap);

		if (StringUtils.isNotBlank(pdfValue)) {

			PdfBean pdfBean = JsonUtils.fromJson(pdfValue, PdfBean.class);

			/**证件号码和识别的证件号码对比,匹配相同更新:成功*/
			if (req.getData().getCertNo().equals(pdfBean.getCertNo())) {

				/**pdf上传文件到服务器*/
				String value = getPdfEncode64(urlMap, req.getData().getBusinessId(), null, null, null);
				/** TODOS 文件服务器上传pdf的测试网关为 http://10.170.10.3/ms-gateway/filesystem/v1/uploadFile*/
				NfsFileDetailRespDataVo nfsFileDetailRespDataVo = uploadPdf(req, urlMap, value);
				if (null == nfsFileDetailRespDataVo) {
					MySlf4j.textInfo("本地pdf上传文件到文件服务器失败");
					updateVxAlipayBillAnalysisReqBean(VxAlipayBillConstantUtils.STATUS_FAIL, req, null,
							billAnalysisReqId);
				} else {
					MySlf4j.textInfo("本地pdf上传文件到文件服务器成功");
					updateVxAlipayBillAnalysisReqBean(VxAlipayBillConstantUtils.STATUS_SUCCESS, req,
							nfsFileDetailRespDataVo, billAnalysisReqId);
				}
				/**保存远程识别的pdf到响应表中*/
				saveVxAlipayOCRData(pdfBean, billAnalysisReqId + "");
			}
		}
	}

}
